package org.demo.test.thread.lock;

import sun.misc.Unsafe;

import java.lang.reflect.Field;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;

public class CAS implements java.io.Serializable {

    private volatile int count;

    private static Unsafe unsafe;

    private static long countOffset;



    static {
        try {
            Field field = Unsafe.class.getDeclaredField("theUnsafe");
            field.setAccessible(true);
            unsafe = (Unsafe)field.get(null);
            countOffset = unsafe.objectFieldOffset(CAS.class.getDeclaredField("count"));
        }catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
    public CAS(int count){
        this.count = count;
    }

    /**
     * 自旋锁的写法，扣减
     */
    public void kj(){
        for (;;){
            int current = this.count;
            int i = current - 1;
            if(i < 0 || unsafe.compareAndSwapInt(this, countOffset, current, i)){
                if(i>=0) {
                    System.out.println(i);
                }
                return;
            }
            System.out.println("自旋.");
        }
    }

    public static void main(String[] args) {
        CAS cas = new CAS(10);
        CountDownLatch countDownLatch = new CountDownLatch(1);
        for (int i=0; i < 10; i++){
            new Thread(()->{
                try {
                    countDownLatch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                cas.kj();
            }).start();
        }
        countDownLatch.countDown();
    }

}
